package com.speed.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.speed.entity.Activiter;
import com.speed.entity.Activtites;
import com.speed.entity.MenberCardStartactBm;
import com.speed.entity.SeatInfo;
import com.speed.interceptor.ActivitesInterceptor;
import com.speed.printer.PrintUtil;
import com.speed.printer.UserInfor;
import com.speed.service.ActiviterService;
import com.speed.service.ActivitesService;
import com.speed.service.MenberCardStarctBmService;
import com.speed.service.SeatService;
import com.speed.temp.SmsTempFactory;
import com.speed.util.GenerationSerialNo;
import com.speed.util.SmsFactory;
import com.speed.util.SmsTempData;
import com.speed.util.StringUtils;
import com.speed.util.html.GenerStaticHTML;
import com.speed.util.html.TemplateData;
import com.speed.util.qc.MatrixToImageWriter;
import com.speed.vo.ActiviterVO;

@Before(ActivitesInterceptor.class)
public class ActiviterController extends Controller {

	public void index() {
		ActivitesService activitesService = enhance(ActivitesService.class);
		List<Activtites> activtites = activitesService.findActivites();
		setAttr("activtites", activtites);
		renderJsp("index.jsp");
	}

	public void content() {

		try {
			// 活动ID
			Integer activitesID = getParaToInt(0);

			ActivitesService activitesService = enhance(ActivitesService.class);
			Activtites activtites = activitesService.findActivtitesById(activitesID);

			// 刷新activtites
			if (activtites != null) {
				getSession().setAttribute("activtites", activtites);
			}

			Activtites activtites2 = (Activtites) getSession().getAttribute("activtites");

			ActiviterService activiterService = enhance(ActiviterService.class);

			Long totalActiviters = activiterService.getTotalActivitersByActivtitesID(
					activtites2 != null ? activtites2.getInt(Activtites.ID) : activitesID);
			setAttr("totalActiviters", totalActiviters);
			System.out.println("来宾人数 ：{ " + totalActiviters + " }");

			Long signeders = activiterService.getSignActivitersByActivtitesID(Boolean.TRUE,
					activtites2 != null ? activtites2.getInt(Activtites.ID) : activitesID);
			System.out.println("签到人数: { " + signeders + " }");
			setAttr("signeders", signeders);

			Long noSigneders = activiterService.getSignActivitersByActivtitesID(Boolean.FALSE,
					activtites2 != null ? activtites2.getInt(Activtites.ID) : activitesID);
			System.out.println("未签到人数:{ " + noSigneders + " }");
			setAttr("noSigneders", noSigneders);

			renderJsp("content.jsp");
		} catch (Exception e) {
			renderText(".....出错！");
		} finally {
		}

	}

	public void signedMan() {
		// 默认起始每页显示数
		int pageSize = 10;
		// 起始页码
		// 已签到的
		int pageNumber = 1;
		// 未签到的
		int pageNumber0 = 1;
		String pageNumberStr = getPara(0);
		if (StrKit.notBlank(pageNumberStr)) {
			pageNumber = getParaToInt(0);
			pageNumber0 = getParaToInt(1);
		}
		Activtites activtites = (Activtites) getSession().getAttribute("activtites");
		ActiviterService activiterService = enhance(ActiviterService.class);
		try {
			Page<Activiter> page = activiterService.findActivitersByPageAndActivitesId(pageNumber, pageSize,
					Boolean.TRUE, activtites.getInt(Activtites.ID));
			setAttr("page", page);
			setAttr("isFirstPage", page.isFirstPage());
			setAttr("isLastPage", page.isLastPage());
			Page<Activiter> page0 = activiterService.findActivitersByPageAndActivitesId(pageNumber0, pageSize,
					Boolean.FALSE, activtites.getInt(Activtites.ID));
			setAttr("page0", page0);
			setAttr("isFirstPage0", page0.isFirstPage());
			setAttr("isLastPage0", page0.isLastPage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderJsp("signed.jsp");
	}

	/**
	 * 签到
	 */
	public void sign() {

		try {
			String pName = "name", pMobile = "mobile", pSignCode = "signCode";
			String name = getPara(pName);
			String mobile = getPara(pMobile);
			String signCode = getPara(pSignCode);
			Activtites activtites = (Activtites) getSession().getAttribute("activtites");
			ActiviterService activiterService = enhance(ActiviterService.class);
			Map<String, Object> params = new HashMap<String, Object>();
			// params.put(Activiter.ACTIVITER_NAME, name);
			params.put(Activiter.SIGN_CODE, signCode);
			params.put(Activiter.ACTIVITER_MOBILE, mobile);
			params.put(Activiter.ACTIVITES_ID, activtites.get(Activtites.ID));
			Activiter activiter = activiterService.getActiviterByCoditionForOne(params);
			if (activiter != null) {
				Activiter activiterUpdate = new Activiter().put(activiter).set(Activiter.SIGN_STATUS, Boolean.TRUE)
						.set(Activiter.SIGN_TIME, new Date());
				boolean update = activiterUpdate.update();
				if (update) {
					print(mobile, activiterUpdate);
				}
			}
			forwardAction("/activiter/content");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 签到码直接签到
	 */
	public void directSign() {

		try {
			JSONObject json = new JSONObject();
			String signCode = getPara("signCode");
			ActiviterService activiterService = enhance(ActiviterService.class);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put(Activiter.SIGN_CODE, signCode);
			Activiter activiter = activiterService.getActiviterByCoditionForOne(params);
			Activtites activtites = (Activtites) getSession().getAttribute("activtites");
			if (activiter != null) {
				if (activiter.getBoolean(Activiter.SIGN_STATUS)) {
					json.put("msg", "您签到过了，请进入活动地点，谢谢合作!");
					renderJson(json.toJSONString());
					return;
				}
				boolean update = activiterService.updateActiviter(
						activiter.set(Activiter.SIGN_STATUS, Boolean.TRUE).set(Activiter.SIGN_TIME, new Date()));
				if (update) {
					print(activiter.getStr(Activiter.ACTIVITER_MOBILE), activiter);
				}
			} else {
				json.put("msg", "签到码不正确，请输入正确的签到码!");
				renderJson(json.toJSONString());
				return;
			}
			renderJson(activiter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void print(String mobile, Activiter activiterUpdate) {
		System.out.println();
		// SmsFactory.INSTANCE.send(mobile, "您已经成功签到，感谢您对本次活动的支持相应.");
		UserInfor userInfor = new UserInfor();
		userInfor.setuName(activiterUpdate.getStr(Activiter.ACTIVITER_NAME));
		userInfor.setCompany("广东坚朗五金制品股份有限公司");
		SeatService seatService = enhance(SeatService.class);
		System.out.println(seatService == null);
		SeatInfo seatInfo = seatService.findSeatInfoByActiviterID(activiterUpdate.getLong(Activiter.ID));
		System.out.println(seatInfo == null);
		System.out.println(userInfor == null);
		if (seatInfo == null) {
			userInfor.setSeatNO("V");
		} else {
			userInfor.setSeatNO("V" + seatInfo.getStr(SeatInfo.SEAT_NO));
		}
		try {
			PrintUtil.genc_print(userInfor);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void regist() {
		renderJsp("regist.jsp");
	}

	/**
	 * 现场报名
	 */
	public void add() {
		Activtites activtites = (Activtites) getSession().getAttribute("activtites");

		Activiter activiter = getModel(Activiter.class);
		MenberCardStarctBmService bmService = enhance(MenberCardStarctBmService.class);
		ActiviterService activiterService = enhance(ActiviterService.class);
		String name = activiter.get(Activiter.ACTIVITER_NAME);
		String mobile = activiter.get(Activiter.ACTIVITER_MOBILE);
		if (StrKit.isBlank(mobile) || StrKit.isBlank(name)) {
			renderJson("{\"msg\":\"临时参加活动人员的姓名和手机为空，请正确填写!\"}");
			return;
		}
		if (mobile.length() != 11) {
			renderJson("{\"msg\":\"手机号码不正确，请正确填写!\"}");
			return;
		}
		Activiter theOne = Activiter.MODEL_DAO.findFirst(
				"select " + Activiter.ACTIVITER_MOBILE + " from " + Activiter.TABLE_NAME + " where "
						+ Activiter.ACTIVITER_MOBILE + " = ? AND " + Activiter.ACTIVITES_ID + " = ? ",
				activiter.get(Activiter.ACTIVITER_MOBILE), activtites.get(Activtites.ID));
		if (theOne != null) {
			renderJson("{\"msg\":\"手机号码出现重复，请正确填写!\"}");
			return;
		}
		// 报名了应缴费后才能得到签到码
		String signCode = GenerationSerialNo.generNo();
		activiter = activiterService.saveActiviter(activiter.set(Activiter.SIGN_CODE, signCode)
				.set(Activiter.SIGN_STATUS, Boolean.FALSE).set(Activiter.ACTIVITES_ID, activtites.get(Activtites.ID))
				.set(Activiter.HD_ID, activtites.get(Activtites.WXACT_ID)));
		// 同步到微信o2o
		Ret ret = new Ret(MenberCardStartactBm.NAME, name);
		if (activtites != null) {
			ret.put(MenberCardStartactBm.RECORD_ID, activtites.get(Activtites.WXACT_ID));
		}
		ret.put(MenberCardStartactBm.MP, mobile);
		ret.put(MenberCardStartactBm.FROM, "QZCRM签到：" + getSession().getAttribute("wrp"));
		ret.put(MenberCardStartactBm.ORDERNUM, GenerationSerialNo.generNo());
		bmService.saveMenberCard(ret);

		System.out.println("PATH : [ " + PathKit.getWebRootPath() + " ]");
		try {
			MatrixToImageWriter.genCode(signCode, mobile,
					PathKit.getWebRootPath() + File.separator + "code" + File.separator + mobile + ".jpg");
			TemplateData td = new TemplateData();
			// 活动人名
			td.setDatas("name", activiter.get(Activiter.ACTIVITER_NAME));
			td.setDatas("qdImg", mobile + ".jpg");
			td.setDatas("signCode", signCode);
			td.setDatas("mobile", mobile);
			td.setDatas("enterprise", activiter.get(Activiter.ACTIVITER_COMPANY));
			// td.setDatas("sex", sex);
			td.setDatas("wrp", getSession().getAttribute("ctx"));
			td.setInPath(PathKit.getWebRootPath() + File.separator + "code");
			td.setOutPath(PathKit.getWebRootPath() + File.separator + "code" + File.separator + mobile + ".html");
			td.setTempName("qd.ftl");
			GenerStaticHTML.create(td);

			TemplateData td2 = new TemplateData();
			// 活动人名
			td2.setDatas("place", activtites.get(Activtites.ACTIVITES_ADDRESS));
			td2.setInPath(PathKit.getWebRootPath() + File.separator + "code");
			td2.setOutPath(
					PathKit.getWebRootPath() + File.separator + "code" + File.separator + "map" + mobile + ".html");
			td2.setTempName("map.ftl");
			GenerStaticHTML.create(td2);

		} catch (Exception e) {
			e.printStackTrace();
		}
		// 发送短信
		SmsFactory.INSTANCE.send(mobile, "你已成功报名参与本次活动");
		renderJson("{\"msg\":\"已经成功添加临时参与活动人员!\"}");
	}

	/**
	 * 签到页搜索内容列表
	 */
	@Before(POST.class)
	public void list() {

		try {
			Activtites activtites = (Activtites) getSession().getAttribute("activtites");
			Integer pageSize = 5;
			Integer page = getParaToInt("page");
			// 0是所有來賓 1 是簽到 2是未簽到
			String flag = getPara("flag");
			String signCode = getPara("signCode");
			Map<String, Object> params = new HashMap<String, Object>();
			if (!"0".equals(flag)) {
				params.put(Activiter.SIGN_STATUS, "1".equals(flag) ? Boolean.TRUE : Boolean.FALSE);
			}
			params.put(Activiter.ACTIVITES_ID, activtites.getInt(Activtites.ID));

			if (StrKit.notBlank(signCode)) {
				// 手机末4位
				if (signCode.length() == 4 && StringUtils.isNumeric(signCode)) {
					params.put(Activiter.ACTIVITER_MOBILE, signCode);
					// 签到码
				} else if (signCode.length() == 8) {
					params.put(Activiter.SIGN_CODE, signCode);
					// 名称
				} else {
					params.put(Activiter.ACTIVITER_NAME, signCode);
				}
			}
			ActiviterService activiterService = enhance(ActiviterService.class);
			Page<Activiter> pageModel = activiterService.findActivitersForPage(page, pageSize, params);
			renderJson(pageModel);
		} catch (Exception e) {
			JSONObject json = new JSONObject();
			json.put("msg", "出现异常");
			renderJson(json.toJSONString());
		}

	}

	// @Before(POST.class)
	public void listTest() {
		Integer pageSize = 10;
		Integer page = 1;
		// 0是所有來賓 1 是簽到 2是未簽到
		String flag = "0";
		Map<String, Object> params = new HashMap<String, Object>();
		if (!"0".equals(flag)) {
			params.put(Activiter.SIGN_STATUS, "1".equals(flag) ? Boolean.TRUE : Boolean.FALSE);
		}
		ActiviterService activiterService = enhance(ActiviterService.class);
		Page<Activiter> pageModel = activiterService.findActivitersForPage(page, pageSize, params);
		renderJson(pageModel);
	}
	
	
	public void test(){
		SmsTempFactory factory = SmsTempFactory.INSTANCE;
		List<String> tempName = factory.getTempName(1);
		System.out.println("temp NAME :{ " +tempName+" }");
		 SmsTempData b = new SmsTempData();
	     b.setName("abc");
	     b.setSignCode("1212132");
	     b.setMobile("13612512547");
		String content = factory.getContent(1, "temp01", b);
		renderText(content);
	}

}